import { useState, useEffect, useRef } from 'react'
import { ciYus } from '../utils/hanZis'
import { useParams } from 'react-router-dom'
import { Swiper, SwiperSlide } from 'swiper/react'
import { Radio, Checkbox } from 'antd'
import { pinYinBaseUrl } from '../utils/config'
import { disruptOrder } from '../utils/tool'
import Examination from '../components/examination'
import 电梯到达铃声 from '/audio/电梯到达铃声.mp3'
import './style/literacy.scss'
import 'swiper/css';

let synth = {}
const 每层动画时间 = 1500
const 进入电梯时间 = 2000
const 离开电梯时间 = 1500
const 电梯开关门时间 = 2000
// const 每层动画时间 = 150
// const 进入电梯时间 = 200
// const 离开电梯时间 = 150
// const 电梯开关门时间 = 200
let hasInitCurrVoice = false
const modes = [{
    label: '识记模式',
    value: 1,
}, {
    label: '答题模式',
    value: 2
}]
export default () => {
    const [swiper, setSwiper] = useState({})
    const { name: paramName } = useParams()
    const { 名称, 楼层s } = ciYus[paramName]
    const { navigate } = window.store
    const [currFloorItem, setCurrFloorItem] = useState(楼层s[0])
    const [speed, setSpeed] = useState(每层动画时间)
    const [voices, setVoices] = useState([])
    const [currVoice, setCurrVoice] = useState(null)
    // const currVoiceRef = useRef({})
    const [currImg, setCurrImg] = useState('')
    const currCi = currFloorItem.词.map(item => item.名称)
    const [currPinyin, setCurrPinyin] = useState('')
    const [mode, setMode] = useState(1)
    const [乱序, set乱序] = useState(false)
    const playerRef = useRef()
    const audioEffectRef = useRef()
    const [literacyStatus, setLiteracyStatus] = useState('')
    console.log('~~名称,楼层s', 名称, 楼层s, speed, currVoice, paramName)
    // currVoiceRef.current = currVoice

    useEffect(() => {
        synth = window.speechSynthesis
        const voices = synth.getVoices()
        // console.log('~~[voices]', voices)
        synth.addEventListener("voiceschanged", (v) => {
            console.log('~~voiceschanged v', v)
            const voices = synth.getVoices()
            const cnVoices = voices.filter(item => item.lang === 'zh-CN')
            setVoices(cnVoices)
            if (!hasInitCurrVoice) {
                setCurrVoice(cnVoices[0])
                hasInitCurrVoice = true
            }
        })
    }, [])

    useEffect(() => {
        const idx = 楼层s.findIndex(item => item.层数 === currFloorItem.层数)
        setTimeout(() => {
            swiper?.slideTo?.(idx)
        }, 进入电梯时间 + 电梯开关门时间)

    }, [currFloorItem])

    const onVoicerClick = (item) => {
        const str = currCi.join(',')
        const utterThis = new SpeechSynthesisUtterance(str)
        utterThis.voice = item
        synth.speak(utterThis)
        setCurrVoice(item)
    }

    const onNumBtnClick = (_item) => {
        setCurrImg('')
        const prevIdx = 楼层s.findIndex(item => item.层数 === currFloorItem.层数)
        const idx = 楼层s.findIndex(item => item.层数 === _item.层数)
        setSpeed(Math.abs(idx - prevIdx) * 每层动画时间)
        setCurrFloorItem(_item)
        setLiteracyStatus('into')
        setTimeout(() => setLiteracyStatus('closeDoor'), 进入电梯时间)
    }

    const read = str => {
        const utterThis = new SpeechSynthesisUtterance(str)
        utterThis.voice = currVoice
        synth.speak(utterThis)
    }

    console.log('~~乱序', 乱序)
    return <div className={'p-literacy ' + paramName}>
        <h1>{名称}</h1>
        <div className='layout'>
            <div className='l'>
                <ul className='btns'>
                    <li className='btn' onClick={() => navigate(-1)}><i className='iconfont i-dianTiKaiMen' /></li>
                    {楼层s.map(item =>
                        <li className={'btn ' + (currFloorItem === item ? 'active' : '')} onClick={() => onNumBtnClick(item)} key={item.层数} >{item.层数}</li>
                    )}
                </ul>
                <dl className='guideMap'>
                    <dt>楼层导览</dt>
                    {楼层s.map(item =>
                        <dd className={'btn '} key={item.层名} >
                            {item.层数 + '. ' + (item.层名 || item.词[0].名称)}
                        </dd>
                    )}
                </dl>
            </div>
            <div className='r'>
                <Radio.Group
                    options={modes}
                    onChange={e => setMode(e.target.value)}
                    value={mode}
                    optionType="button"
                    buttonStyle="solid"
                />
                {mode === 2
                    ? <Examination words={currCi} playerRef={playerRef} setCurrPinyin={setCurrPinyin} paramName={paramName} read={read} />
                    : <>
                        {/* 现在第{currFloorItem.层数}层 */}
                        <div className={'zuCi ' + literacyStatus}>
                            <div className='scene' style={{ animationDuration: (literacyStatus === 'into' ? 进入电梯时间 : 离开电梯时间) + 'ms' }}>
                                <Swiper
                                    direction='vertical'
                                    speed={speed}
                                    spaceBetween={50}
                                    slidesPerView={1}
                                    onSlideChange={(v) => console.log('~~slide change', v)}
                                    onSwiper={(_swiper) => setSwiper(_swiper)}
                                    onSlideChangeTransitionEnd={() => {
                                        // 播放音效，开门延迟
                                        audioEffectRef.current.play()
                                        setTimeout(() => {
                                            setLiteracyStatus('openDoor')
                                            setTimeout(() => setLiteracyStatus('goout'), 电梯开关门时间)
                                        }, 1000)
                                    }}
                                >
                                    {楼层s.map(item =>
                                        <SwiperSlide key={item.层数} >
                                            {/* {(乱序?disruptOrder(JSON.parse(JSON.stringify(item.词))):item.词).map(item => */}
                                            {(乱序 ? disruptOrder(item.词.slice()) : item.词).map(item =>
                                                <span className={'ciYus ' + (currFloorItem === item ? 'active' : '')} key={item.名称} onClick={() => {
                                                    setCurrImg(item.img)
                                                    if (paramName === 'pinYin') {
                                                        const pinyin = item.名称.replace('ü', 'v').toLocaleLowerCase()
                                                        setCurrPinyin(`${pinYinBaseUrl + pinyin}.mp3`)
                                                        playerRef.current.addEventListener("canplaythrough", (event) => {
                                                            /* 音频可以播放；如果权限允许则播放 */
                                                            playerRef.current.play();
                                                        })
                                                    } else {
                                                        read(item.名称)
                                                    }
                                                }}>{item.名称}</span>
                                            )}
                                            <Checkbox onChange={v => set乱序(v.target.checked)}>重新排列</Checkbox>
                                            <div className='img' style={{ backgroundImage: `url(${currImg})` }} />
                                        </SwiperSlide>
                                    )}
                                </Swiper>
                            </div>
                            {/* 因用mask挖掉一块，所以无法在内部或用伪元素画门 */}
                            <div className='literacyBox' style={{ animationDuration: (literacyStatus === 'into' ? 进入电梯时间 : 离开电梯时间) + 'ms' }}>
                                <div className='door'>
                                    <div className='left' style={{ animationDuration: 电梯开关门时间 + 'ms' }} />
                                    <div className='right' style={{ animationDuration: 电梯开关门时间 + 'ms' }} />
                                </div>
                                <div className='bg' />
                                {/* <div className='door right' /> */}
                            </div>

                        </div>
                        <h3>选择播音员</h3>
                        {paramName === 'pinYin'
                            ? <div>读拼音只一位播音员哦~</div>
                            : <ul className='voicer'>
                                {voices.map((item) =>
                                    <li onClick={() => onVoicerClick(item)} className={item.name === currVoice.name ? 'active' : ''} key={item.name}>{item.name.split(' ')[1]}</li>
                                )}
                            </ul>}
                    </>}
            </div>
        </div>
        <audio src={currPinyin} ref={playerRef} />
        <audio src={电梯到达铃声} ref={audioEffectRef} />
    </div>
}